<template>
    <el-upload class="avatar-uploader" action="http://127.0.0.1:3007/user/avator" :headers="headers"
        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
            <Plus />
        </el-icon>
    </el-upload>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { ElMessage, UploadProps, UploadUserFile } from 'element-plus'


const props = defineProps({
    modelValue: {
        type: Object,
        default: () => {
            return {
                imageUrl: "",
                originalName: "",
                size: 0,
                mimeType: "",
                userId: ""
            }
        }
    },
    accept: {
        type: Array,
        default: ["jpg", "jpeg", "png"]
    },
    maxSize: {
        type: Number,
        default: 5, // 单位M
    }
})

const emits = defineEmits(["update:modelValue"])

const headers = reactive({
    Authorization: localStorage.getItem("token")
})

const imageUrl = computed(() => {
    return props.modelValue.imageUrl
})
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
) => {
    if (response.status == 200) {
        emits("update:modelValue", response.data)
    }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const arr = rawFile.name.split(".")
    const type = arr[arr.length - 1]
    if (!props.accept.includes(type)) {
        ElMessage.error(`请上传${props.accept.join(",")}格式文件`)
        return false
    } else if (rawFile.size / 1024 / 1024 > props.maxSize) {
        ElMessage.error(`文件最大不超过${props.maxSize}M`)
        return false
    }
    return true
}
</script>
<style lang='scss' scoped>
.avatar-uploader {
    width: 120px;
    height: 120px;
    text-align: center;
    line-height: 120px;
    border: 1px dotted #d5d5d5;
}

:deep(.el-upload.el-upload--text) {
    width: 100%;
    height: 100%;

    img {
        width: 100%;
        height: 100%;
    }
}
</style>